//var Koa = require('koa')
//var Path = require('path')
//var Router = require('koa-router')
//var webpack = require('webpack')
//var webpackConfig = require('./webpack.config')
//
//const app = new Koa()
//
//// webpack编译器
//var compiler = webpack(webpackConfig);
//
//// webpack-dev-server中间件
//var devMiddleware = require('webpack-dev-middleware')(compiler, {
//  publicPath: webpackConfig.output.publicPath,
//  stats: {
//    colors: true,
//    chunks: false
//  }
//});
//
//app.use(function*(next) {
//  devMiddleware
//  yield next
//})
//
//const viewRouter = new Router()
//viewRouter.get('/:viewname?', function *(next) {
//
//  console.log(this.params)
//
//  var viewname = this.params.viewname
//    ? this.params.viewname + '.html'
//    : 'index.html';
//
//  var filepath = Path.join(compiler.outputPath, viewname);
//  // 使用webpack提供的outputFileSystem
//  compiler.outputFileSystem.readFile(filepath, (err, result) => {
//    if (err) {
//      // something error
//      return next(err);
//    }
//
//    this.headers.set('content-type', 'text/html');
//    this.body = result
//  });
//})
//
//app.use(viewRouter.routes())
//
//app.listen(9000);


var express = require('express')
var webpack = require('webpack')
var webpackConfig = require('./webpack.config')
var path = require('path')
var onProxy = require('./proxy')

var app = express();

// webpack编译器
var compiler = webpack(webpackConfig);

// webpack-dev-server中间件
var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  }
});

app.use(devMiddleware)

app.use(function(req, res, next) {
  if (req.url.startsWith('/ref')) {
    onProxy(req, res)
  } else {
    next()
  }
})

// 路由
app.get('/:viewname?', function(req, res, next) {
  let viewname
  if (req.params.viewname && req.params.viewname !== '') {
    viewname = req.params.viewname + '.html'
  } else {
    viewname = 'home.html'
  }

  let filepath = path.join(compiler.outputPath, viewname);

  // 使用webpack提供的outputFileSystem
  compiler.outputFileSystem.readFile(filepath, function(err, result) {
    if (err) {
      // something error
      return next(err);
    }
    res.set('content-type', 'text/html');
    res.send(result);
    res.end();
  });
});

module.exports = app.listen(9000, function(err) {
  if (err) {
    // do something
    return;
  }

  console.log('Listening at http://localhost:' + 9000 + '\n')
})
